package com.android.launcher3.widget;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;

import com.android.launcher3.R;

public class SwitchButton extends FrameLayout {

    private View tvOff;
    private View tvOn;
    private View vOff;
    private View vOn;

    private boolean checked;

    private OnCheckedChangeListener listener;

    public SwitchButton(@NonNull Context context) {
        super(context);
        init();
    }

    public SwitchButton(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public SwitchButton(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {

        LayoutInflater.from(getContext()).inflate(R.layout.layout_switch, this, true);
        tvOff = findViewById(R.id.tv_off);
        tvOn = findViewById(R.id.tv_on);
        vOff = findViewById(R.id.v_off);
        vOn = findViewById(R.id.v_on);

        setOnClickListener(v -> {
            checked = !checked;

            onCheckChange();

        });
    }

    private void onCheckChange() {
        if (!checked) {
            tvOff.setVisibility(VISIBLE);
            tvOn.setVisibility(INVISIBLE);
            vOff.setVisibility(INVISIBLE);
            vOn.setVisibility(VISIBLE);
        } else {
            tvOff.setVisibility(INVISIBLE);
            tvOn.setVisibility(VISIBLE);
            vOff.setVisibility(VISIBLE);
            vOn.setVisibility(INVISIBLE);
        }

        if (listener != null) {
            listener.onCheckedChanged(SwitchButton.this, checked);
        }
    }


    void setSelect(boolean checked) {
        this.checked = checked;
        onCheckChange();
    }

    public void setListener(OnCheckedChangeListener listener) {
        this.listener = listener;
    }

    public static interface OnCheckedChangeListener {
        /**
         * Called when the checked state of a compound button has changed.
         *
         * @param buttonView The compound button view whose state has changed.
         * @param isChecked  The new checked state of buttonView.
         */
        void onCheckedChanged(SwitchButton buttonView, boolean isChecked);
    }

}
